#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GansuLongnanPolicy(BaseTaxPolicySpider):
    name = 'gansu_longnan_wu_policy'
    
    province = '甘肃省'
    city: str = "陇南市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                },
                "DOWNLOAD_TIMEOUT": 200,
                # 'CONCURRENT_REQUESTS': 1,
                "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 407],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url, path in [
            ['武都区人民政府', "武都区", "https://www.gslnwd.gov.cn/zfxxgk/public/column/32128522?type=4&catId=142201361&action=list", "首页>信息公开首页"],
            ['文县人民政府', "文县", "https://www.lnwx.gov.cn/zfxxgk/public/column/32130683?type=4&catId=68722254&action=list", "首页>信息公开首页>信息公开专题首页>文县人民政府>政府文件>按公文文种分类>县政府文件"],
            ['两当县人民政府', "两当县", "https://www.ldxzf.gov.cn/zfxxgk/public/column/4663967?type=4&catId=8459066&action=list", "首页>信息公开首页>信息公开专题首页>两当县人民政府办公室>政府文件>按公文文种分类>两政发"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item, 'path': path})

    def parse_list(self, response, **kwargs):
        # print(response.url)
        meta = response.meta
        prev_item = meta.get('item')
        elem_list = response.xpath(
            "//ul[contains(@class, 'contantList')]//li[@class]//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//tr[contains(@id, 'line')]//a[(contains(@href, '.htm') or @title) and not(starts-with(text(), '|'))]/ancestor::tr[string-length(string(.))>=9] | "
            "//*[contains(@class, 'govnewslist')]//tr//a[(contains(@href, '.htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//*[contains(@class, 'xxgk_nav_list')]//li//a[(contains(@href, '.htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9]"
        )
        print(len(elem_list), response.url)
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""//span/text()""").re_first(r"\d{4}-\d{2}-\d{2}")
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jsp' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl gansu_longnan_wu_policy".split())
